var express = require('express');
var path = require('path');
var http = require('http');
var io = require('socket.io');
var fs = require('fs');
var app = express();
var clients = {};
var logins = {};
var hisotry = {};

var port = (process.env.VCAP_APP_PORT || 8080);

app.use(require('body-parser').urlencoded({extended: true}))
app.use(express.static(__dirname));
/*
app.get('/online', function (req, res) {
    for (var id in clients) {
        res.write((id + '(' + clients[id].userId + ')').link('/send/' + id) + "<br/>");
    }
    res.end();
});*/

app.get('/user/online', function (req, res) {
    res.send(logins);
});


app.get('/user/send/:uid', function (req, res) {
    var socket;
    var message = {event: req.param('event'), data: req.param('data')};
    var domain = req.query.domain;
    var login_list = logins[domain]||{};
    if ((message.data.charAt(0) === '{' || message.data.charAt(0) === '[') && (message.data.charAt(message.data.length - 1) === '}' || message.data.charAt(message.data.length - 1) === ']')) {
        try {
            message.data = JSON.parse(message.data);
        } catch (e) {
        }
    }
    if (login_list[req.params.uid] && (socket = clients[login_list[req.params.uid]])) {
        if (message.event) {
            socket.emit(message.event, message.data);
        } else {
            socket.send(message.data);
        }
        res.send({sts: true});
    } else {
        //用户不在线报错离线消息
        if (!hisotry[req.params.uid])hisotry[req.params.uid] = [];
        hisotry[req.params.uid].push(message);
        res.send({sts: false});
    }
});


app.post('/sender/:uid', function (req, res) {
    var socket;
    var message = {event: req.body.event, data: req.body.data};
    var domain = req.query.domain;
    var login_list = logins[domain]||{};
    var id = req.param('uid');
    if ((message.data.charAt(0) === '{' || message.data.charAt(0) === '[') && (message.data.charAt(message.data.length - 1) === '}' || message.data.charAt(message.data.length - 1) === ']')) {
        try {
            message.data = JSON.parse(message.data);
        } catch (e) {
        }
    }
    if (login_list[id] && (socket = clients[login_list[id]])) {
        if (message.event) {
            socket.emit(message.event, message.data);
        } else {
            socket.send(message.data);
        }
        res.send({sts: true});
    } else {
        //用户不在线报错离线消息
        if (!hisotry[id])hisotry[id] = [];
        hisotry[id].push(message);
        res.send({sts: false});
    }
});

app.get('/send/:id', function (req, res) {
    var id = req.param("id");
    if (clients[id]) {
        var socket = clients[id];
        socket.send('hello');
        //socket.emit('test event', 'hello');
    }
    res.end();
});


var server = http.createServer(app).listen(port, function () {
    console.log('start listen ' + port);
});

io.listen(server).on('connection', function (socket) {

    console.log(socket.id, "connect");
    var query = socket.handshake.query;
    if(!query.domain){
        socket.disconnect(true);
        return false;
    }
    var domain = query.domain;
    if(!logins[domain])logins[domain] = {};
    var login_list = logins[domain];

    socket.on('disconnect', function () {
        console.log(socket.id, "disconnect");
        if (login_list[socket.userId]) {
            delete login_list[socket.userId];
        }
        if (clients[socket.id])delete  clients[socket.id];
    });

    socket.on('login', function (data) {
        data.userId = data.userId || 0;
        if(!data.userId || login_list[data.userId]){
            if (clients[socket.id])delete  clients[socket.id];
            socket.disconnect(true);
            return;
        }
        socket.userId = data.userId;
        if (socket.userId) {
            console.log(data, 'login');
            login_list[socket.userId] = socket.id;
            if (hisotry[socket.userId]) {
                var h = hisotry[socket.userId];
                for (var i = 0; i < h.length; i++) {
                    socket.emit(h[i].event, h[i].data);
                }
                delete hisotry[socket.userId];
            }
        }
    });

    socket.on('logout', function () {
        if (login_list[socket.userId]) {
            delete login_list[socket.userId];
        }
        socket.userId = 0;
    });

    socket.on('message', function (message) {
        console.log(message)
    });
    clients[socket.id] = socket;
});